package com.eqdd.yiqidian.ui.yiqigou

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import chihane.jdaddressselector.BottomDialog
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.AreaBean
import com.eqdd.yiqidian.bean.ProductBean
import com.eqdd.yiqidian.bean.utils.MultiChooseBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonConverter
import com.eqdd.yiqidian.kotlin.imgPathPreview
import com.eqdd.yiqidian.kotlin.popMenu
import com.eqdd.yiqidian.ui.SingleChooseActivity
import com.eqdd.yiqidian.ui.companyspace.ProductInfoActivity
import com.eqdd.yiqidian.utils.ImageUtil
import com.eqdd.yiqidian.utils.MultiChooseTestUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.cache.CacheMode
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.model.Response
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCCoolHelper
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.activity_recyclerview_refresh_search.*
import kotlinx.android.synthetic.main.activity_title.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import java.util.*

/**
 * Created by jhj on 18-8-18.
 */
class ProductSearchActivity : BaseActivity() {

    private var pageNum = 0
    private var position: String = ""
    private var productType: String = ""
    private var areaBean: List<AreaBean>? = null
    private var areaDialog: BottomDialog? = null
    private var inputManager: InputMethodManager? = null
    private var slimAdapterEx: SlimAdapterEx<ProductBean>? = null
    private var mvcHelper: MVCCoolHelper<List<ProductBean>>? = null

    override fun initBinding() {
        setContentView(R.layout.activity_recyclerview_refresh_search)
        initTopTitleBar(View.VISIBLE, "搜索")
        tv_right.text = "筛选"
        popMenu(arrayListOf("产品类别", "产品地区", "重置筛选"), tv_right) { dialog, pos ->
            if (pos == 0) {
                startActivityForResult<SingleChooseActivity>(1000, Config.TITLE to "产品类别", Config.TYPE to 2)
            } else if (pos == 1) {
                initAreaDialog()
            } else if (pos == 2) {
                position = ""
                productType = ""
                mvcHelper?.refresh()
            }
        }
        searchBarMask.setOnTouchListener(keyboardState)
    }

    override fun initData() {

        val list = arrayListOf<ProductBean>()
        mvcHelper = MVCCoolHelper<List<ProductBean>>(coolRefreshView)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.addItemDecoration(DividerLineItemDecoration(this))
        slimAdapterEx = SlimAdapterEx.create()
                .register<ProductBean>(R.layout.list_item_166, SlimInjector<ProductBean> { data, injector ->
                    val str = String.format(Locale.CHINA, "产品价格：￥%s元", data?.productPrice)
                    val span = SpannableString(str)
                    span.setSpan(ForegroundColorSpan(Color.RED), 5, str.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                    injector
                            ?.with<ImageView>(R.id.iv_image) { view ->
                                if (data?.image?.isNotBlank() == true) {
                                    view.visibility = View.VISIBLE
                                    view.onClick {
                                        imgPathPreview(data.image)
                                    }
                                    Glide.with(this)
                                            .asBitmap()
                                            .apply(ImageUtil.optionsNormal)
                                            .load(data.image)
                                            .into(object : SimpleTarget<Bitmap>() {
                                                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>) {
                                                    val scale = resource.width.toDouble() / resource.height.toDouble()
                                                    if (scale < 0.85 && scale > 0.65) {
                                                        view.scaleType = ImageView.ScaleType.CENTER_CROP
                                                    }
                                                    view.background = BitmapDrawable(resources, resource)
                                                }
                                            })
                                } else {
                                    view.visibility = View.GONE
                                }
                            }
                            ?.text(R.id.tv_name, String.format(Locale.CHINA, "产品名称：%s", data?.productName))
                            ?.text(R.id.tv_post, span)
                            ?.text(R.id.tv_msg, String.format(Locale.CHINA, "发货地址：%s", data?.area))
                            ?.text(R.id.tv_label, data?.productType)
                })
                .attachTo(recyclerView)
                .updateData(list as List<*>?) as SlimAdapterEx<ProductBean>?
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener { recyclerView, position, v ->
                    val data = slimAdapterEx?.getDataItem(position)
                    startActivity<ProductInfoActivity>(Config.ID to data?.id)
                }

        requestData()
    }

    private fun requestData() {
        val dataSource = ModelRx2DataSource<ProductBean>(ModelRx2DataSource.OnLoadSource<ProductBean> { page, register ->
            val params = HttpParams()

            val url = if (et_search?.text.isNullOrBlank() && position == "" && productType == "") {
                HttpConfig.BASE_URL + HttpConfig.SHOPPING_PRODUCT
            } else {
                params.put("para", et_search.text.toString())
                params.put("productType", productType)
                params.put("area", position)
                HttpConfig.BASE_URL + HttpConfig.SHOPPING_PRODUCT_SEARCH
            }

            if (page == 1) {
                pageNum = 0
            }
            OkGo.post<HttpResult<List<ProductBean>>>(url)
                    .params("page", pageNum)
                    .params(params)
                    .converter(object : JsonConverter<HttpResult<List<ProductBean>>>() {
                        override fun test() {
                            super.test()
                        }
                    })
                    .adapt(FlowableBody<HttpResult<List<ProductBean>>>())
                    .flatMap({ result ->
                        pageNum = result.page
                        Flowable.just(
                                if (result.items == null) arrayListOf<ProductBean>() else result.items
                        )
                    })

        }, 10)

        mvcHelper?.setDataSource(dataSource)
        mvcHelper?.adapter = slimAdapterEx
        mvcHelper?.refresh()
    }

    override fun setView() {
        et_search.setOnKeyListener { v, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
                (inputManager as InputMethodManager?)?.hideSoftInputFromWindow(et_search.windowToken, 0)
                mvcHelper?.refresh()
            }
            false
        }
    }

    private val keyboardState = View.OnTouchListener { _, _ ->
        searchBarMask.visibility = View.GONE
        et_search.addTextChangedListener(textChangedListener)

        if (inputManager == null) {
            inputManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager?.showSoftInput(et_search, InputMethodManager.SHOW_FORCED)
        }
        recyclerView.setOnTouchListener { _, _ ->
            (inputManager as InputMethodManager?)?.hideSoftInputFromWindow(et_search.windowToken, 0)
            if (et_search.text.isNullOrBlank()) {
                searchBarMask.visibility = View.VISIBLE
            }
            false
        }
        false
    }

    private val textChangedListener = object : TextWatcher {
        override fun afterTextChanged(p0: Editable?) {
            if (et_search.text.isNullOrBlank()) {
                tv_right.visibility = View.GONE
                position = ""
                productType = ""
                requestData()
            } else {
                tv_right.visibility = View.VISIBLE
            }
        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

        }

    }


    private fun initAreaDialog() {
        if (areaDialog == null) {
            OkGo.post<List<AreaBean>>(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS)
                    .params("type", 0)
                    .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
                    .cacheKey(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS + "0")
                    .execute(object : DialogCallBack<List<AreaBean>>(this) {
                        override fun onSuccess(response: Response<List<AreaBean>>) {
                            areaBean = response.body()
                            initAreaPicker()
                        }

                        override fun onCacheSuccess(response: Response<List<AreaBean>>?) {
                            super.onCacheSuccess(response)
                            areaBean = response?.body()
                            initAreaPicker()
                        }
                    })
        } else {
            areaDialog?.show()
        }
    }


    private fun initAreaPicker() {
        val multiChooseBeen = ArrayList<MultiChooseBean>()
        areaBean?.let {
            multiChooseBeen.addAll(it)
        }
        areaDialog = MultiChooseTestUtil().getAreaDialog(this@ProductSearchActivity, 3, multiChooseBeen) { d, a ->
            areaDialog?.dismiss()
            position = ""
            for (iSelectAble in a) {
                position += iSelectAble.name
            }
            mvcHelper?.refresh()
        }
        areaDialog?.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
            productType = data?.getStringExtra("data") ?: ""
            mvcHelper?.refresh()
        }
    }

}